{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding:cp1252 -*-\n",
    "\n",
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    2+2,\n",
    "    \n",
    "    4 / 2,  #除法运算 (/) 总是返回浮点数\n",
    "    \n",
    "    4.1 // 2,\n",
    "    \n",
    "    15 // 2 + 15 % 2,\n",
    "    \n",
    "    2 ** 3,\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "#交互模式下，上次输出的表达式会赋给变量 _\n",
    "[1] + _"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('''\n",
    "Usage: thingy\n",
    "    -h\n",
    "    -H hostname\n",
    "    ''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('''\\\n",
    "Usage: thingy\n",
    "    -h\n",
    "    -H hostname\\\n",
    "    ''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    'py'  'thon',\n",
    "    'py' , 'thon',\n",
    "    'py' + 'thon',\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "word = \"Python\"\n",
    "\n",
    "{'word[0]':word[0], 'word[5]':word[5]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    word[-1],\n",
    "    word[-2],\n",
    "    word[-6],\n",
    "    word[-0],\n",
    "    word[0:2],\n",
    "    word[2:5],\n",
    "    word[:2],\n",
    "    word[4:],\n",
    "    word[-2:],\n",
    "    word[:2] + word[2:],\n",
    "    word[:4] + word[4:],\n",
    "    word[2:-2],\n",
    "    #word[23],\n",
    "    word[:23],\n",
    "    len(word)\n",
    "]  \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b = 0, 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "while a < 1000:\n",
    "    print(a)\n",
    "    a, b = b, a+b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b = 0, 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "while a < 1000000:\n",
    "    print(a, end=',')\n",
    "    p = a\n",
    "    a = b\n",
    "    b = p + b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {},
   "outputs": [],
   "source": [
    "help(print)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "squares = [1, 4, 9, 16, 25]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    squares,\n",
    "    squares[0],\n",
    "    squares[-3:],\n",
    "    squares + [36, 49],\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17",
   "metadata": {},
   "outputs": [],
   "source": [
    "cubes = [1, 8, 27, 65, 125]\n",
    "cubes[3] = 4 ** 3\n",
    "cubes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18",
   "metadata": {},
   "outputs": [],
   "source": [
    "cubes.append(6 ** 3)\n",
    "cubes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19",
   "metadata": {},
   "outputs": [],
   "source": [
    "rgb = ['Red', 'Green', 'Blue']\n",
    "rgba = rgb\n",
    "id(rgb) == id(rgba)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20",
   "metadata": {},
   "outputs": [],
   "source": [
    "rgb = ['Red', 'Green', 'Blue']\n",
    "rgba = rgb[:]\n",
    "id(rgb) == id(rgba)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21",
   "metadata": {},
   "outputs": [],
   "source": [
    "rgba.append('alph')\n",
    "rgb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22",
   "metadata": {},
   "outputs": [],
   "source": [
    "# x = int(input(\"Please enter an integer: \"))\n",
    "x = 1\n",
    "\n",
    "if x < 0:\n",
    "    x = 0\n",
    "    print('Negative changed to zero')\n",
    "elif x == 0:\n",
    "    print('Zero')\n",
    "elif x == 1:\n",
    "    print('Single')\n",
    "else:\n",
    "    print('More')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23",
   "metadata": {},
   "outputs": [],
   "source": [
    "words = ['cat', 'window', 'defenestrate']\n",
    "for w in words:\n",
    "    print(f'{w:12s}', f'{len(w):2d}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24",
   "metadata": {},
   "outputs": [],
   "source": [
    "users = {'Hans': 'active', \\\n",
    "         'Eleonore': 'inactive', \\\n",
    "         '景太郎': 'active'}\n",
    "\n",
    "for user, status in users.copy().items():\n",
    "    if status == 'inactive':\n",
    "        del users[user]\n",
    "        users[user+\"'s son\"] = 'active'\n",
    "users.items()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25",
   "metadata": {},
   "outputs": [],
   "source": [
    "users = {'Hans': 'active', \\\n",
    "         'Eleonore': 'inactive', \\\n",
    "         '景太郎': 'active'}\n",
    "\n",
    "active_users = {}\n",
    "for user, status in users.items():\n",
    "    if status == 'active':\n",
    "        active_users[user] = 'inactive'\n",
    "active_users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dir(), end = '')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(0, 5):\n",
    "    print(i, end = ' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28",
   "metadata": {},
   "outputs": [],
   "source": [
    "list(range(5, 10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29",
   "metadata": {},
   "outputs": [],
   "source": [
    "list(range(0, 10, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30",
   "metadata": {},
   "outputs": [],
   "source": [
    "list(range(-10, -100, -30))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = ['Mary', 'had', 'a', 'little', 'lamb']\n",
    "\n",
    "for i in range(len(a)):\n",
    "    print(i, a[i], end = ';    ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32",
   "metadata": {},
   "outputs": [],
   "source": [
    "range(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33",
   "metadata": {},
   "outputs": [],
   "source": [
    "range(5, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {},
   "outputs": [],
   "source": [
    "#help(range)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35",
   "metadata": {},
   "outputs": [],
   "source": [
    "sum(range(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36",
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in range(2, 10):\n",
    "    for x in range(2, n):\n",
    "        if n % x == 0:\n",
    "            print(f\"{n} equals {x} * {n // x}\")\n",
    "            break\n",
    "        else:\n",
    "            print(f\"{n}  {x}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(2, 2):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38",
   "metadata": {},
   "outputs": [],
   "source": [
    "for num in range(2, 10):\n",
    "    if num % 2 == 0:\n",
    "        print(f\"Found an even number {num}\")\n",
    "        continue\n",
    "    print(f\"Found an {' odd':4s} number {num}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39",
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in range(2, 10):\n",
    "    for x in range(2, n):\n",
    "        if n % x == 0:\n",
    "            print(n, 'equals', x, '*', n//x)\n",
    "            break\n",
    "    else:\n",
    "        print(n, 'is a prime number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40",
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in range(2, 10):\n",
    "    for x in range(2, n):\n",
    "        if n % x == 0:\n",
    "            print(n, 'equals', x, '*', n//x)\n",
    "            break\n",
    "        else:\n",
    "            print(n, 'is a prime number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41",
   "metadata": {},
   "outputs": [],
   "source": [
    "#while True:\n",
    "#    pass\n",
    "\n",
    "class MyEmptyClass:\n",
    "    pass\n",
    "\n",
    "def initlog(*args):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42",
   "metadata": {},
   "outputs": [],
   "source": [
    "def http_error(status):\n",
    "    match status:\n",
    "        case 400:\n",
    "            return \"Bad request\"\n",
    "        case 404 | 401 | 403:\n",
    "            return \"Not found\"\n",
    "        case 418:\n",
    "            return \"I'm a teapot\"\n",
    "        case _:\n",
    "            return \"Something's wrong with the internet\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43",
   "metadata": {},
   "outputs": [],
   "source": [
    "def point(point):\n",
    "  match point:\n",
    "    case (0, 0):\n",
    "        print(\"Origin\")\n",
    "    case (0, y):\n",
    "        print(f\"Y={y}\")\n",
    "    case (x, 0):\n",
    "        print(f\"X={x}\")\n",
    "    case (x, y):\n",
    "        print(f\"X={x}, Y={y}\")\n",
    "    case _:\n",
    "        raise ValueError(\"Not a point\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44",
   "metadata": {},
   "outputs": [],
   "source": [
    "point((1, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45",
   "metadata": {},
   "outputs": [],
   "source": [
    "point([1, 2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46",
   "metadata": {},
   "outputs": [],
   "source": [
    "#point({1:2})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Point:\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "def where_is(point):\n",
    "  match point:\n",
    "    case Point(x=0, y=0):\n",
    "        print(\"Origin\")\n",
    "    case Point(x=0, y=y):\n",
    "        print(f\"Y={y}\")\n",
    "    case Point(x=x, y=0):\n",
    "        print(f\"X={x}\")\n",
    "    case Point():\n",
    "        print(\"Somewhere else\")\n",
    "    case _:\n",
    "        print(\"Not a point\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48",
   "metadata": {},
   "outputs": [],
   "source": [
    "where_is(Point(1, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Point2:\n",
    "    __match_args__ = ('y', 'x')\n",
    "    def __init__(self, x, y):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "\n",
    "def where_ismatch(point2):\n",
    "  match point2:\n",
    "      case []:\n",
    "        print(\"No points\")\n",
    "      case [Point2(0, 0)]:\n",
    "        print(\"The origin\")\n",
    "      case [Point2(x, y)] if x == y:\n",
    "        print(f\"Y=X at {x}\")\n",
    "      case [Point2(x, y)]:\n",
    "        print(f\"Single point {x}, {y}\")\n",
    "      case [Point2(0, y1), Point2(0, y2)]:\n",
    "        print(f\"Two on the Y axis at {y1}, {y2}\")\n",
    "      case _:\n",
    "        print(\"Something else\")\n",
    "\n",
    "where_ismatch([Point2(5, 0), Point2(9, 0)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50",
   "metadata": {},
   "outputs": [],
   "source": [
    "where_ismatch([Point2(3, 4)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum\n",
    "class Color(Enum):\n",
    "    RED = 'red'\n",
    "    GREEN = 'green'\n",
    "    BLUE = 'blue'\n",
    "\n",
    "def color_is(color):\n",
    "    match color:\n",
    "        case Color.RED:\n",
    "            print(\"I see red!\")\n",
    "        case Color.GREEN:\n",
    "            print(\"Grass is green\")\n",
    "        case Color.BLUE:\n",
    "            print(\"I'm feeling the blues :(\")\n",
    "\n",
    "color_is(Color.BLUE) != color_is('red')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib(n):\n",
    "    '''Print a Fibonacci series less than n.'''\n",
    "    a, b = 0, 1\n",
    "    while a < n:\n",
    "        print(a, end=' ')\n",
    "        a, b = b, a+b\n",
    "    print()\n",
    "\n",
    "fib(2000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53",
   "metadata": {},
   "outputs": [],
   "source": [
    "help(fib)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54",
   "metadata": {},
   "outputs": [],
   "source": [
    "help(color_is)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55",
   "metadata": {},
   "outputs": [],
   "source": [
    "fib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56",
   "metadata": {},
   "outputs": [],
   "source": [
    "f = fib\n",
    "f(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(fib(0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58",
   "metadata": {},
   "outputs": [],
   "source": [
    "fib(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib2(n):\n",
    "    '''Return a list containing the Fibonacci series up to n.'''\n",
    "    result = []\n",
    "    a, b = 0, 1\n",
    "    while a < n:\n",
    "        result.append(a)\n",
    "        a, b = b, a+b\n",
    "    return result\n",
    "\n",
    "fib2(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60",
   "metadata": {},
   "outputs": [],
   "source": [
    "fib2(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61",
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib3(n):\n",
    "    'return语句不带表达式参数时，返回None。函数执行完毕退出也返回None。'\n",
    "    1 == 1\n",
    "\n",
    "print(fib3(0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62",
   "metadata": {},
   "outputs": [],
   "source": [
    "help(fib3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ask_ok(prompt, retries=2, reminder='Please try again!'):\n",
    "    while True:\n",
    "        reply = random.choice(['y', 'n', 'ye', 'yes', 'no', 'nop', 'nope', 'orther string'])#input(prompt)\n",
    "        if reply in {'y', 'ye', 'yes'}:\n",
    "            return True\n",
    "        if reply in {'n', 'no', 'nop', 'nope'}:\n",
    "            return False\n",
    "        retries -= 1\n",
    "        if retries < 0:\n",
    "            #raise ValueError('invalid user response')\n",
    "            print('invalid user response')\n",
    "            return False\n",
    "        print(reminder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ask_ok2(prompt='', retries=2, reminder='Please try again!'):\n",
    "    '''\n",
    "    默认参数：\n",
    "    Python 要求所有没有默认值的参数（如 prompt）必须在调用时提供\n",
    "    即使您修改了函数内部逻辑（如注释掉异常），函数的参数要求没有改变\n",
    "    错误发生在调用阶段，而非函数执行阶段\n",
    "    '''\n",
    "    while True:\n",
    "        reply = random.choice(['y', 'n', 'ye', 'yes', 'no', 'nop', 'nope', 'orther string'])#input(prompt)\n",
    "        if reply in {'y', 'ye', 'yes'}:\n",
    "            return True\n",
    "        if reply in {'n', 'no', 'nop', 'nope'}:\n",
    "            return False\n",
    "        retries -= 1\n",
    "        if retries < 0:\n",
    "            #raise ValueError('invalid user response')\n",
    "            print('invalid user response')\n",
    "            return False\n",
    "        print(reminder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65",
   "metadata": {},
   "outputs": [],
   "source": [
    "ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66",
   "metadata": {},
   "outputs": [],
   "source": [
    "ask_ok('OK to overwrite the file?')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67",
   "metadata": {},
   "outputs": [],
   "source": [
    "ask_ok('OK to overwrite the file?', 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68",
   "metadata": {},
   "outputs": [],
   "source": [
    "ask_ok2()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(a, L=[]):\n",
    "    '默认值只计算一次。但默认值为列表、字典或类实例等【可变对象】时，会产生与该规则不同的结果。'\n",
    "    L.append(a)\n",
    "    return L\n",
    "\n",
    "print(f(1))\n",
    "print(f(2))\n",
    "print(f(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(a, L=None):\n",
    "    '''默认值只计算一次。但默认值为列表、字典或类实例等【可变对象】时，会产生与该规则不同的结果。\n",
    "    不想在后续调用之间共享默认值时，应以如下方式编写函数'''\n",
    "    if L is None:\n",
    "        L = []\n",
    "    L.append(a)\n",
    "    return L\n",
    "\n",
    "print(f(1))\n",
    "print(f(2))\n",
    "print(f(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71",
   "metadata": {},
   "outputs": [],
   "source": [
    "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n",
    "    '''\n",
    "    函数调用时，关键字参数必须跟在位置参数后面。\n",
    "    所有传递的关键字参数都必须匹配一个函数接受的参数（比如，actor 不是函数 parrot 的有效参数）​，\n",
    "    关键字参数的顺序并不重要。这也包括必选参数，​（比如，parrot(voltage=1000) 也有效）​。\n",
    "    '''\n",
    "    \n",
    "    print(\"-- This parrot wouldn't\", action, end=' ')\n",
    "    print(\"if you put\", voltage, \"volts throuth it.\")\n",
    "    print(\"-- Lovely plumage, the\", type)\n",
    "    print(\"-- It's\", state, \"!\\n\")\n",
    "\n",
    "parrot(1000)\n",
    "parrot(voltage=1000)\n",
    "parrot(voltage=1000000, action='VOOOOOM')\n",
    "parrot(action='VOOOOOM', voltage=1000000)\n",
    "parrot('a million', 'bereft of life', ' jump')\n",
    "parrot('a thousand', state='pushing up the daisies')\n",
    "\n",
    "'''\n",
    "parrot()                        #缺失必需的参数\n",
    "parrot(voltage=5.0, ' dead')    #关键字参数后存在非关键字参数\n",
    "parrot(110,voltage=220)         #同一参数重复赋值\n",
    "parrot(actor=' John Cleese')    #未很大的关键字参数\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72",
   "metadata": {},
   "outputs": [],
   "source": [
    "def cheeseshop(kind, *arguments, **keywords):\n",
    "    '''\n",
    "    *name形参接收一个元组，该元组包含形参列表之外的位置参数\n",
    "    **name形参接收一个字典，该字典包含形参列表之外的关键字参数\n",
    "    '''\n",
    "    print(\"-- Do you have any\", kind, \"?\")\n",
    "    print(\"-- I'm sorry, we're all out of\", kind)\n",
    "    for arg in arguments:\n",
    "        print(arg)\n",
    "    print(\"-\" * 40)\n",
    "    for kw in keywords:\n",
    "        print(kw, \":\", keywords[kw])\n",
    "\n",
    "cheeseshop(\"Limburger\", \"It's very runny, sir.\",\n",
    "           \"It's really very, VERY runny, sir.\",\n",
    "           shopkeeper=\"Michael Palin\",\n",
    "           client=\"John Cleese\",\n",
    "           sketch=\"Cheese Shop Sketch\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73",
   "metadata": {},
   "outputs": [],
   "source": [
    "def standard_arg(arg):\n",
    "    print(arg)\n",
    "\n",
    "def pos_only_arg(arg, /):\n",
    "    print(arg)\n",
    "\n",
    "def kwd_only_arg(*, arg):\n",
    "    print(arg)\n",
    "\n",
    "def combined_example(pos_only, /, standard, *, kwd_only):\n",
    "    print(pos_only, standard, kwd_only)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74",
   "metadata": {},
   "outputs": [],
   "source": [
    "standard_arg(2)\n",
    "standard_arg(arg=2)\n",
    "\n",
    "pos_only_arg(1)\n",
    "#pos_only_arg(arg=2)\n",
    "\n",
    "#kwd_only_arg(3)\n",
    "kwd_only_arg(arg=3)\n",
    "\n",
    "#combined_example(1, 2, 3)\n",
    "combined_example(1, 2, kwd_only=3)\n",
    "combined_example(1, standard=2, kwd_only=3)\n",
    "#combined_example(pos_only=1, standard=2, kwd_only=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75",
   "metadata": {},
   "outputs": [],
   "source": [
    "def foo(name, **kwds):\n",
    "    '''\n",
    "    **kwds中不能存在关键字参数name=\n",
    "    '''\n",
    "    return 'name' in kwds\n",
    "\n",
    "def foo2(name, /, **kwds):\n",
    "    return 'name' in kwds\n",
    "\n",
    "[\n",
    "#foo(1, **{'name': 2})    # name被同时通过位置（1）和关键字（name=2）赋值两次\n",
    "#foo2(0, **{'name': 2})    #\n",
    "\n",
    "#foo(1, name=2)\n",
    "foo(name=2),\n",
    "foo2(1, name=2)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76",
   "metadata": {},
   "outputs": [],
   "source": [
    "def concat(*args, sep=\"/\"):\n",
    "    return sep.join(args)\n",
    "\n",
    "[\n",
    "concat(\"earth\", \"mars\", \"venus\"),\n",
    "concat(\"earth\", \"mars\", \"venus\", sep=\".\")\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77",
   "metadata": {},
   "outputs": [],
   "source": [
    "args = [3, 6]\n",
    "\n",
    "[\n",
    "    list(range(3, 6)),\n",
    "    list(range(*args))\n",
    "]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78",
   "metadata": {},
   "outputs": [],
   "source": [
    "d = {\"voltage\":\"four million\", \"state\":\"bleedin' demised\", \"action\":\"VOOM\"}\n",
    "\n",
    "def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\n",
    "    '''\n",
    "    函数调用时，关键字参数必须跟在位置参数后面。\n",
    "    所有传递的关键字参数都必须匹配一个函数接受的参数（比如，actor 不是函数 parrot 的有效参数）​，\n",
    "    关键字参数的顺序并不重要。这也包括必选参数，​（比如，parrot(voltage=1000) 也有效）​。\n",
    "    '''\n",
    "    print(\"-- This parrot wouldn't\", action, end=' ')\n",
    "    print(\"if you put\", voltage, \"volts throuth it.\")\n",
    "    print(\"-- Lovely plumage, the\", type)\n",
    "    print(\"-- It's\", state, \"!\\n\")\n",
    "\n",
    "parrot(**d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79",
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_incrementor(n):\n",
    "    return lambda x:x + n\n",
    "\n",
    "f = make_incrementor(11)\n",
    "[\n",
    "    f(0),\n",
    "    f(1),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80",
   "metadata": {},
   "outputs": [],
   "source": [
    "pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n",
    "#pairs.sort(key=lambda pair:pair[1])\n",
    "pairs.sort(key=lambda pair:pair[1][1])\n",
    "\n",
    "[\n",
    "    pairs\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(parrot.__doc__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(ham: str, eggs: str = 'eggs') -> str:\n",
    "    print(\"Annotations:\", f.__annotations__)\n",
    "    print(\"Arguments:\", ham, eggs)\n",
    "    return ham + ' and ' + eggs\n",
    "\n",
    "f('ham')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83",
   "metadata": {},
   "outputs": [],
   "source": [
    "L1, L2 = [], []\n",
    "L3 = [0]\n",
    "L1.append(1)\n",
    "L2[len(L2):] = [2]\n",
    "L3[len(L3)-1] = 3\n",
    "\n",
    "[L1, L2, L3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84",
   "metadata": {},
   "outputs": [],
   "source": [
    "L4, L5 = [], []\n",
    "L4.extend(L1 + L2 + L3)\n",
    "L5[len(L5):] = L1 + L2 + L3\n",
    "[L4, L5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85",
   "metadata": {},
   "outputs": [],
   "source": [
    "['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'].count('apple')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86",
   "metadata": {},
   "outputs": [],
   "source": [
    "['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'].count('tangerine')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87",
   "metadata": {},
   "outputs": [],
   "source": [
    "['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'].index('banana')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88",
   "metadata": {},
   "outputs": [],
   "source": [
    "['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'].index('banana', 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89",
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']\n",
    "\n",
    "fruits.append('grape')\n",
    "\n",
    "fruits.reverse()\n",
    "\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90",
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits.sort()\n",
    "fruits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91",
   "metadata": {},
   "outputs": [],
   "source": [
    "stack = [3, 4, 5]\n",
    "stack.append(6)\n",
    "stack.append(7)\n",
    "print(stack)\n",
    "stack.pop()\n",
    "stack.pop()\n",
    "stack.pop()\n",
    "print(stack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92",
   "metadata": {},
   "outputs": [],
   "source": [
    "squares1 = [] #, squares2, squares3 = [], [], []\n",
    "\n",
    "for x in range(10):\n",
    "    squares1.append(x**2)\n",
    "\n",
    "squares2 = list(map(lambda x:x**2, range(10)))\n",
    "\n",
    "squares3 = [x**2 for x in range(10)]\n",
    "\n",
    "[squares1, squares2, squares3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "\n",
    "queue = deque(['Eric', 'John', 'Michael'])\n",
    "\n",
    "queue.append('Terry')\n",
    "queue.append('Graham')\n",
    "\n",
    "print(queue)\n",
    "\n",
    "queue.popleft()\n",
    "queue.popleft()\n",
    "\n",
    "print(queue)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95",
   "metadata": {},
   "outputs": [],
   "source": [
    "combs = []\n",
    "for x in [1, 2, 3]:\n",
    "    for y in [3, 1, 4]:\n",
    "        if x != y:\n",
    "            combs.append((x, y))\n",
    "\n",
    "[\n",
    "    combs,\n",
    "    [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96",
   "metadata": {},
   "outputs": [],
   "source": [
    "vec = [-4, -2, 0, 2, 4]\n",
    "\n",
    "[\n",
    "    [x*2 for x in vec],\n",
    "    [x for x in vec if x>= 0],\n",
    "    [abs(x) for x in vec]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97",
   "metadata": {},
   "outputs": [],
   "source": [
    "freshfruit = ['    banana', '  loganberry', 'passion fruit  ']\n",
    "[weapon.strip() for weapon in freshfruit]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "[x, x**2 for x in range(6)]\n",
    "'''\n",
    "[(x, x**2) for x in range(6)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99",
   "metadata": {},
   "outputs": [],
   "source": [
    "vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
    "\n",
    "''.join(str(num) for elem in vec for num in elem)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "100",
   "metadata": {},
   "outputs": [],
   "source": [
    "    vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
    "\n",
    "\n",
    "    ''.join(str(num) for elem in vec for num in elem),\n",
    "    ''.join(str(num) for sublist in vec for num in sublist),\n",
    "    (str(num) for sublist in vec for num in sublist),\n",
    "    [str(num) for sublist in vec for num in sublist]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "101",
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import pi\n",
    "[str(round(pi, i)) for i in range(1, 16)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "102",
   "metadata": {},
   "outputs": [],
   "source": [
    "matrix = [\n",
    "    [1, 2, 3, 4],\n",
    "    [5, 6, 7, 8],\n",
    "    [9,10,11,12]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "103",
   "metadata": {},
   "outputs": [],
   "source": [
    "list(zip(*matrix))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "104",
   "metadata": {},
   "outputs": [],
   "source": [
    "[[row[i] for row in matrix] for i in range(4)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "105",
   "metadata": {},
   "outputs": [],
   "source": [
    "[row[i] for row in matrix for i in range(4)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "106",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [-1, 1, 66.25, 333, 333, 1234.5]\n",
    "print(a)\n",
    "del a[0]\n",
    "print(a)\n",
    "del a[2:4]\n",
    "print(a)\n",
    "del a[:]\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "107",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = 12345, 54321, 'hello!'\n",
    "print(t[0])\n",
    "print(t)\n",
    "u = t, (1, 2, 3, 4, 5)\n",
    "print(u)\n",
    "#t[0] = 88888\n",
    "v = ([1, 2, 3], [3, 2, 1])\n",
    "print(v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "108",
   "metadata": {},
   "outputs": [],
   "source": [
    "empty = ()\n",
    "singleton = 'hello',\n",
    "singleton2 = 'hello'\n",
    "[len(empty), len(singleton), len(singleton2), singleton, singleton2, empty]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "109",
   "metadata": {},
   "outputs": [],
   "source": [
    "w = 12345, '12345', [12345]\n",
    "x, y, z = w\n",
    "m, n, l = 12345, '12345', [12345]\n",
    "\n",
    "#[print(i) for i in (x, y, z)]\n",
    "#[print(i) for i in (m, n, l)]\n",
    "\n",
    "print(*(x, y, z), sep=\"\\n\")  # 高效单行解决方案\n",
    "\n",
    "# 仅限临时调试（仍不推荐）\n",
    "_ = [print(i) for i in (x, y, z)]  # 用_表示忽略结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "110",
   "metadata": {},
   "outputs": [],
   "source": [
    "basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n",
    "print(basket)\n",
    "[\n",
    "'orange' in basket,\n",
    "'crabgrass' in basket\n",
    "]\n",
    "\n",
    "a = set('abracadabra')\n",
    "b = set('alacazam')\n",
    "\n",
    "[\n",
    "    a,\n",
    "    a - b,\n",
    "    a | b,\n",
    "    a & b,\n",
    "    a ^ b,\n",
    "    (a | b) - (a & b),\n",
    "    {x for x in (a | b) if x not in (a & b)}\n",
    "    \n",
    "]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "111",
   "metadata": {},
   "outputs": [],
   "source": [
    "tel = {'jack':4098, 'sape':4139}\n",
    "tel['guido'] = 4127\n",
    "print(tel)\n",
    "print(tel['jack'])\n",
    "del tel['sape']\n",
    "tel['irv'] = 4127\n",
    "print(tel)\n",
    "print(list(tel))\n",
    "print(sorted(tel))\n",
    "[\n",
    "    'guido' in tel,\n",
    "    'jack' not in tel\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "112",
   "metadata": {},
   "outputs": [],
   "source": [
    "dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "113",
   "metadata": {},
   "outputs": [],
   "source": [
    "dict((('sape', 4139), ('guido', 4127), ('jack', 4098)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "114",
   "metadata": {},
   "outputs": [],
   "source": [
    "dict(sape = 4139, guido = 4127, jack = 4098)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "115",
   "metadata": {},
   "outputs": [],
   "source": [
    "{x:x**2 for x in (2, 4, 6)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "116",
   "metadata": {},
   "outputs": [],
   "source": [
    "knights = {'gallahad':'the pure', 'robin':'the brave'}\n",
    "for k, v in knights.items():\n",
    "    print(k, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "117",
   "metadata": {},
   "outputs": [],
   "source": [
    "knights = ['gallahad the pure', 'robin the brave']\n",
    "for k, v in enumerate(knights):\n",
    "    print(k, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "118",
   "metadata": {},
   "outputs": [],
   "source": [
    "questions = ['name', 'quest', 'favorite color', 'sport', 'age', 'favourite food']\n",
    "\n",
    "answers = ['lancelot', 'the holy grail', 'blue', 'running', 'ten', 'ice cream' ]\n",
    "\n",
    "for q, a in zip(questions, answers):\n",
    "    print(f'What is your {q}? It is {a}.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "119",
   "metadata": {},
   "outputs": [],
   "source": [
    "basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n",
    "\n",
    "for i in sorted(basket):\n",
    "    print(i)\n",
    "\n",
    "print()\n",
    "\n",
    "for f in sorted(set(basket)):\n",
    "    print(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "120",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "raw_data = [56.2, float('NaN'), 51.7, 55.3, float('NaN'), 47.8]\n",
    "filtered_data = []\n",
    "for value in raw_data:\n",
    "    if not math.isnan(value):\n",
    "        filtered_data.append(value)\n",
    "\n",
    "filtered_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "121",
   "metadata": {},
   "outputs": [],
   "source": [
    "string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n",
    "int1, int2, int3 = 0, 2, 4\n",
    "non_zero = int1 or int2 or int3\n",
    "non_null = string1 or string2 or string3\n",
    "[\n",
    "    non_null,\n",
    "    non_zero\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "122",
   "metadata": {},
   "outputs": [],
   "source": [
    "# name = user_input or \"default\"\n",
    "\n",
    "# value = obj and obj.attr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "123",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    (1, 2, 3) < (1, 2, 4),\n",
    "\n",
    "    [1, 2, 3] < [1, 2, 4],\n",
    "\n",
    "    'ABC' < 'C' < 'Pascal' < 'Python',\n",
    "\n",
    "    (1, 2, 3, 4) < (1, 2, 4),\n",
    "\n",
    "    (1, 2) < (1, 2, -1),\n",
    "\n",
    "    (1, 2, 3) == (1.0, 2.0, 3.0),\n",
    "\n",
    "    (1, 2, ('ab', 'a')) < (1, 2, ('abc', 'a'), 4),\n",
    "\n",
    "    (1, 2, ('abc', 'ab')) < (1, 2, ('abc', 'a'), 4),\n",
    "\n",
    "    (1, 2, ('abc', 'a')) < (1, 2, ('abc', 'a'), 4)\n",
    "\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "124",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "125",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "126",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "127",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "128",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.ps1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "129",
   "metadata": {},
   "outputs": [],
   "source": [
    "sys.ps2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "130",
   "metadata": {},
   "outputs": [],
   "source": [
    "sys.path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "131",
   "metadata": {},
   "outputs": [],
   "source": [
    "#print('fibo:', dir(fibo), sep=' ')\n",
    "print()\n",
    "#print('sys:', dir(sys), sep=' ')\n",
    "print()\n",
    "#print('dir():', dir(), sep=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "132",
   "metadata": {},
   "outputs": [],
   "source": [
    "import builtins\n",
    "print('builtins', dir(builtins), sep=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "133",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mypkg.math.fibo\n",
    "[\n",
    "mypkg.math.fibo.fib_mypkg(1000),\n",
    "mypkg.math.fibo.fib2_mypkg(1000),\n",
    "mypkg.math.fibo.__name__\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "134",
   "metadata": {},
   "outputs": [],
   "source": [
    "from mypkg.math.fibo import fib_mypkg as f1\n",
    "f2 = mypkg.math.fibo.fib2_mypkg\n",
    "[\n",
    "    f1(500),\n",
    "    f2(500)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "135",
   "metadata": {},
   "outputs": [],
   "source": [
    "!python mypkg\\math\\fibo.py 50\n",
    "!python -m mypkg.math.fibo 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "136",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''运行%run后，fibo.py中定义的名称均会导入命名空间'''\n",
    "%run mypkg\\math\\fibo.py 50\n",
    "print()\n",
    "%run -m mypkg.math.fibo 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "137",
   "metadata": {},
   "outputs": [],
   "source": [
    "fib2_mypkg(900)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "138",
   "metadata": {},
   "outputs": [],
   "source": [
    "#from mypkg.math.fibo import *\n",
    "fib2(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "139",
   "metadata": {},
   "outputs": [],
   "source": [
    "year = 2016\n",
    "event = 'Learning Python'\n",
    "f'Results of the {year} {event}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "140",
   "metadata": {},
   "outputs": [],
   "source": [
    "yes_votes = 42_572_654\n",
    "total_votes = 85_705_149\n",
    "percentage = yes_votes / total_votes\n",
    "'{:-19} Yes votes {:4.6%}'.format(yes_votes, percentage)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "141",
   "metadata": {},
   "outputs": [],
   "source": [
    "s = 'Hello, world.'\n",
    "[\n",
    "str(s),\n",
    "repr(s),\n",
    "str(1/7),\n",
    "print(s),\n",
    "print(repr(s)),\n",
    "repr((3.142, '3.142'))\n",
    "\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "142",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "f'{math.pi:.66f}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "143",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = {'Sjoerd':4127.11, 'Jack':4098.666, 'Dcab':7678.8888}\n",
    "for name, phone in table.items():\n",
    "    print(f'{name:10s}  ==> {phone:15f}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "144",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = {'Sjoerd':4127, 'Jack':4098, 'Dcab':7678}\n",
    "for name, phone in table.items():\n",
    "    print(f'{name:10s}  ==> {phone:15d}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "145",
   "metadata": {},
   "outputs": [],
   "source": [
    "animals = 'eels'\n",
    "print(f'{animals}')\n",
    "print(f'\"!a\" 应用 ascii() : {animals!a}')\n",
    "print(f'\"!s\" 应用 str(): {animals!s}')\n",
    "print(f'\"!r\" 应用 repr(): {animals!r}')\n",
    "\n",
    "print(f'\\n{table=}   {animals=}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "146",
   "metadata": {},
   "outputs": [],
   "source": [
    "[\n",
    "    '{} {}!'.format('Hello', 'World'),\n",
    "    '{0} {1}!'.format('Hello', 'World'),\n",
    "    '{1} {0}!'.format('Hello', 'World'),\n",
    "    '{0} {1} and {other}!'.format('Hello', 'World', other='Others'),\n",
    "    '{} {}!'.format('Hello', 'World'),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "147",
   "metadata": {},
   "outputs": [],
   "source": [
    "table = {'Sjoerd':4127, 'Jack':4098, 'Dcab':7678}\n",
    "[\n",
    "'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table),\n",
    "'',\n",
    "'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "148",
   "metadata": {},
   "outputs": [],
   "source": [
    "#print(vars())\n",
    "table = {k:str(v) for k, v in vars().items()}\n",
    "#print(table)\n",
    "message = \"\".join([f'{k}:' + '{' + k + '};' for k in table.keys()])\n",
    "#print(message)\n",
    "#print(message.format(**table))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "149",
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in range(1, 11):\n",
    "    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x**3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "150",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('testfile.data', 'a+') as tf:\n",
    "    #tf.write('this is the 1st line.\\n')\n",
    "    #print(tf.readlines())\n",
    "    tf.seek(0)\n",
    "    tf.readline()\n",
    "    tf.readline()\n",
    "    for line in tf:\n",
    "        print(line)\n",
    "\n",
    "#%cat testfile.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('testfile.data', 'rb+') as tf:\n",
    "    #tf.write('this is the 1st line.\\n')\n",
    "    #print(tf.readlines())\n",
    "    tf.seek(-33, 2)\n",
    "    for line in tf:\n",
    "        print(line)\n",
    "\n",
    "#%cat testfile.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "152",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('testbfile', 'wb+') as tbf:\n",
    "    tbf.write(b'This is the first line')\n",
    "\n",
    "with open('testbfile', 'r') as tbf:\n",
    "    print(tbf.readline())\n",
    "    tbf.seek(0)\n",
    "    print(tbf.read(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "153",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "x = [1, 'simple', 'list']\n",
    "with open('testjson', 'w+') as tj:\n",
    "    json.dump(x, tj)\n",
    "\n",
    "with open('testjson', 'r') as tj:\n",
    "    y = json.load(tj)\n",
    "\n",
    "print(y)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "154",
   "metadata": {},
   "outputs": [],
   "source": [
    "def division1(x, y):\n",
    "    try:\n",
    "        return x/y\n",
    "    except ZeroDivisionError:\n",
    "        print('Zero Division Error')\n",
    "\n",
    "def division2(x, y):\n",
    "    try:\n",
    "        return x/y\n",
    "    except:\n",
    "        print('Some Error')\n",
    "\n",
    "def division(x, y):\n",
    "    return x/y\n",
    "\n",
    "[division1(6, 7),\n",
    "division2(2, 0),\n",
    "division2(2, '2'),\n",
    "#division1(2, '2'),\n",
    "division2(3, 0),\n",
    "division2(8, 8)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "155",
   "metadata": {},
   "outputs": [],
   "source": [
    "def division1(x, y):\n",
    "    try:\n",
    "        return x/y\n",
    "    except ZeroDivisionError:\n",
    "        print('Zero Division Error')\n",
    "\n",
    "def division2(x, y):\n",
    "    try:\n",
    "        return x/y\n",
    "    except Exception as error:\n",
    "        print(error)\n",
    "\n",
    "def division(x, y):\n",
    "    return x/y\n",
    "\n",
    "[division1(6, 7),\n",
    "division1(2, 0),\n",
    "division2(2, '2'),\n",
    "#division1(2, '2'),\n",
    "division2(3, 0),\n",
    "division2(8, 8)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "156",
   "metadata": {},
   "outputs": [],
   "source": [
    "def scope_test():\n",
    "    '''命名空间，声明变量时nonlocal与global的区别'''\n",
    "    def do_local():\n",
    "        spam = \"local spam\"\n",
    "\n",
    "    def do_nonlocal():\n",
    "        nonlocal spam\n",
    "        spam = \"nonlocal spam\"\n",
    "\n",
    "    def do_global():\n",
    "        global spam\n",
    "        spam = spam + ' + ' + \"global spam\"\n",
    "\n",
    "    spam = \"test spam\"\n",
    "    do_local()\n",
    "    print(\"After local assignment:\", spam)\n",
    "    do_nonlocal()\n",
    "    print(\"After nonlocal assignment:\", spam)\n",
    "    do_global()\n",
    "    print(\"After global assignment:\", spam)\n",
    "\n",
    "spam = 'init global spam'\n",
    "scope_test()\n",
    "print(\"In global scope:\", spam)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "157",
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyClass:\n",
    "    \"\"\"类对像的数据属性，不需要在定义类时声明\"\"\"\n",
    "    i = 12345\n",
    "\n",
    "    def f(self):\n",
    "        return 'hello world'\n",
    "x = MyClass()\n",
    "x.counter = 1\n",
    "while x.counter < 10:\n",
    "    x.counter = x.counter * 2\n",
    "print(x.counter)\n",
    "del x.counter\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "158",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''限制基类方法被重写'''\n",
    "\n",
    "class Base:\n",
    "    def __init__(self):\n",
    "        self.setup()  # 危险：派生类可能未初始化\n",
    "        \n",
    "    def setup(self):\n",
    "        pass\n",
    "\n",
    "        \n",
    "class SafeBase:\n",
    "    def __init__(self):\n",
    "        self._safe_setup()\n",
    "        \n",
    "    def _safe_setup(self):\n",
    "        \"\"\"非虚方法，确保基类行为\"\"\"\n",
    "        # 基础初始化代码\n",
    "        self.setup()\n",
    "        \n",
    "    def setup(self):\n",
    "        pass\n",
    "\n",
    "class Derived(Base):\n",
    "    def __init__(self):\n",
    "        self.data = []\n",
    "        super().__init__()\n",
    "        \n",
    "    def setup(self):\n",
    "        self.data.append(42)  # 此时data已初始化吗？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "159",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "160",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "161",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "162",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "163",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
